package com.tt.aile.upload.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.List;

/**
 * @author 86176 shkstrat
 * @date 2020/9/24 - 16:12
 *
 * 实现文件上传
 */
@Service
public class UploadService {

    //日志
    private static final Logger LOGGER = LoggerFactory.getLogger(UploadService.class);

    //文件类型白名单
    private static final List<String> CONTENN_TYPES = Arrays.asList("image/gif","image/jpeg","image/png","image/png");

    public String uploadImage(MultipartFile file) {

        //得到原始文件名
        String originalFilename = file.getOriginalFilename();
        try {

            //1.判断是否为照片
            String contentType = file.getContentType();
            if(!CONTENN_TYPES.contains(contentType)){
                LOGGER.info("文件上传失败：{}，文件类型不合法",originalFilename);
                return null;
            }

            //2.经验文件内容
            BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
            if (bufferedImage==null){
                LOGGER.info("文件上传失败：{}，文件内容不合法",originalFilename);
                return null;
            }

            //3.保存到服务器
            file.transferTo(new File("D:\\idea\\aileImage",originalFilename));

            //4.返回url路径
            return "http://image.aile.com/"+originalFilename;
        } catch (IOException e) {
            LOGGER.info("文件上传失败：{}，服务器出粗",originalFilename);
            e.printStackTrace();
            return null;
        }
    }
}
